﻿using System.Collections.Generic;
using Clipping.Infrastructure.Interfaces;
using Clipping.Infrastructure.Models;

namespace Clipping.SearchEnginePageParsers
{
	public class GoogleWebPageParser : ISearchEnginePageParse
	{
		public void Parse(string html, out List<News> news, out string nextPageUrl)
		{
			news = new List<News>();
			nextPageUrl = null;
			HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
			doc.LoadHtml(html);

			var liNav = doc.CreateNavigator();
			var lis = liNav.Select("//li[@class='g']");
			while (lis.MoveNext())
			{

				var li = lis.Current;
				var id = li.GetAttribute("id", "");
				if (id != "newsbox" && id != "imagebox_bigimages")
				{
					News n = new News();
					//取标题和链接
					var linkNode = li.SelectSingleNode("descendant::h3[@class='r']/a");
					if (linkNode != null)
					{
						n.Title = linkNode.Value;
						n.Url = linkNode.GetAttribute("href", "");
					}

					//取媒体
					var mediaNode = li.SelectSingleNode("descendant::div[@class='f kv']/cite");
					if (mediaNode != null)
					{
						n.Media = System.Web.HttpUtility.HtmlDecode(mediaNode.Value);
					}

					//取摘要
					var summaryNode = li.SelectSingleNode("descendant::span[@class='st']");
					if (summaryNode != null)
					{
						n.Summary = summaryNode.Value;
					}


					news.Add(n);
				}
			}

			var nextPageNode = liNav.SelectSingleNode("//a[@id='pnnext']");
			if (nextPageNode != null)
			{

				nextPageUrl = nextPageNode.GetAttribute("href", "");
			}
			else
			{
				var footDiv = liNav.SelectSingleNode("//div[@id='foot']");
				if (footDiv != null)
				{
					var aList = footDiv.Select("descendant::a");
					if (aList != null)
					{
						while (aList.MoveNext())
						{
							var a = aList.Current;
							if (a.Value.Contains("下一页"))
							{
								nextPageUrl = a.GetAttribute("href", "");
								break;
							}
						}
					}
				}
			}
		}
	}
}
